package guowei.gulicart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import guowei.common.utils.R;
import guowei.gulicart.feign.ProductFeign;
import guowei.gulicart.interceptor.CartInterceptor;
import guowei.gulicart.service.CartService;
import guowei.gulicart.vo.Cart;
import guowei.gulicart.vo.CartItem;
import guowei.gulicart.vo.CartUserInfo;
import guowei.gulicart.vo.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeign feign;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 根据skuId和数量 添加商品商品进购物车，具体是登陆购物车还是临时购物车，根据options区分
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> options = getRedisOptions();

        CartItem item = new CartItem();
//  异步编排实现以下两步:
//    一：redis中没有存入商品
        if (options.get(skuId.toString()) == null){
            //      1.远程查询sku信息
            CompletableFuture<Void> skuInfo1 = CompletableFuture.runAsync(() -> {
                R skuInfo = feign.getSkuInfo(skuId);
                SkuInfo info = (SkuInfo) skuInfo.getData("skuInfo", new TypeReference<SkuInfo>() {
                });
                if (info != null){
                    item.setSkuId(skuId);
                    item.setCount(num);
                    item.setImage(info.getSkuDefaultImg());
                    item.setPrice(info.getPrice());
                    item.setTitle(info.getSkuTitle());
                }
            }, executor);

            //      2.远程查询sku的销售属性信息
            CompletableFuture<Void> skuInfo2 = CompletableFuture.runAsync(() -> {
                List<String> saleAttrs = feign.getSaleAttrs(skuId);
                if (saleAttrs != null){
                    item.setSkuAttr(saleAttrs);
                }
            }, executor);

            //       3.必须等待所有异步任务全部完成，
            CompletableFuture.allOf(skuInfo1,skuInfo2).get();

            String s = JSON.toJSONString(item);
            options.put(skuId.toString(), s);

            System.out.println("这是个新商品");
            return item;
        }else {
            String s = (String) options.get(skuId.toString());
            CartItem cartItem = JSON.parseObject(s, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);

            String s1 = JSON.toJSONString(cartItem);
            options.put(skuId.toString(),s1);
            System.out.println("此商品已经存在");
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItemByItemId(Long skuId) {
        BoundHashOperations<String, Object, Object> options = getRedisOptions();

        String sss = (String) options.get(skuId.toString());
        CartItem item = JSON.parseObject(sss, CartItem.class);

        return item;
    }

    @Override
    public Cart getCartItems() {

        CartUserInfo userInfo = CartInterceptor.thread.get();
        Cart cart = new Cart();

        //判断是否登录
        if (userInfo.getUserId() != null){
            BoundHashOperations<String, Object, Object> options = getRedisOptions();
            //临时购物车有商品，则合并进登陆购物车
            String userKey = userInfo.getUserKey();
            List<Object> values = redisTemplate.opsForHash().values("ganjiuwanle:cart" + userKey);
            List<CartItem> list = values.stream().map(val -> {
                CartItem item = JSON.parseObject(val.toString(), CartItem.class);
                try {
//              合并每一个item,进登陆购物车
                    addToCart(item.getSkuId(),item.getCount());
                }catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return item;
            }).collect(Collectors.toList());
            List<Object> list1 = options.values();
            List<CartItem> collect = list1.stream().map(val -> {
                CartItem item = JSON.parseObject(val.toString(), CartItem.class);
                return item;
            }).collect(Collectors.toList());
            cart.setItems(collect);
            //合并之后删除临时购物车
            redisTemplate.delete("ganjiuwanle:cart" + userKey);
        }else {
            //未登录
            BoundHashOperations<String, Object, Object> options = getRedisOptions();
            List<Object> values = options.values();

            List<CartItem> list = values.stream().map(val -> {
                CartItem item = JSON.parseObject(val.toString(), CartItem.class);
                return item;
            }).collect(Collectors.toList());
            cart.setItems(list);
        }
        return cart;
    }

    @Override
    public void changeChecked(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> options = getRedisOptions();
        CartItem cartItem = getCartItemByItemId(skuId);
        cartItem.setCheck((check==1?true:false));
        String s = JSON.toJSONString(cartItem);
        options.put(skuId.toString(),s);
    }


    @Override
    public void numChangee(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> options = getRedisOptions();
        CartItem item = getCartItemByItemId(skuId);
        item.setCount(num);
        String s = JSON.toJSONString(item);
        options.put(skuId.toString(),s);
    }

    @Override
    public void deleteRedis(Long skuId) {
        BoundHashOperations<String, Object, Object> options = getRedisOptions();
        options.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getOrderItems(String userkey) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps("ganjiuwanle:cart"+userkey);

        List<Object> values = operations.values();
        List<CartItem> cartItems = values.stream().map(item -> {
            CartItem item1 = JSON.parseObject(item.toString(), CartItem.class);
            return item1;
        }).collect(Collectors.toList());

        List<CartItem> items = cartItems.stream().filter(cartItem -> {
            Boolean check = cartItem.getCheck();
            return check;
        }).collect(Collectors.toList());
        return items;
    }

    /**
     * 解决feign远程调用丢失请求头情况。
     * @return
     */
    @Override
    public List<CartItem> getOrderItemsNoKeys() {
        CartUserInfo cartUserInfo = CartInterceptor.thread.get();
        BoundHashOperations<String, Object, Object> options = getRedisOptions();
        List<Object> values = options.values();
        List<CartItem> cartItems = values.stream().map(item -> {
            CartItem item1 = JSON.parseObject(item.toString(), CartItem.class);
//  获取到最新价格
            BigDecimal newPrice = feign.getNewPriceBySkuId(item1.getSkuId());
            item1.setPrice(newPrice);
            return item1;
        }).collect(Collectors.toList());

        List<CartItem> items = cartItems.stream().filter(cartItem -> {
            Boolean check = cartItem.getCheck();
            return check;
        }).collect(Collectors.toList());
        return items;
    }


    //绑定操作redis的options
    private BoundHashOperations<String, Object, Object> getRedisOptions() {
        //  判断是登录用户还是临时用户
        String cartkey = "";
        CartUserInfo cartUserInfo = CartInterceptor.thread.get();
        if (cartUserInfo.getUserId() != null){
            cartkey = "ganjiuwanle:cart"+ cartUserInfo.getUserId();
        }else{
            cartkey = "ganjiuwanle:cart"+ cartUserInfo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartkey);
        return operations;
    }
}
